package com.highper.common.mq;

import com.alibaba.fastjson.JSONObject;
import com.highper.common.sehcma.ContextHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;

import java.util.UUID;

/**
 * @Author ZhangGJ
 * @Date 2022/01/29 10:48
 */
@Slf4j
public class SendHalfMessageRocketMQ {

    @Autowired
    private static RocketMQTemplate rocketMQTemplate;

    public SendHalfMessageRocketMQ(RocketMQTemplate rocketMQTemplate) {
        SendHalfMessageRocketMQ.rocketMQTemplate = rocketMQTemplate;
    }

    public static int sendHalfMessage(Object o, String group, String topic) {
        JSONObject messageData = new JSONObject();
        messageData.put("payload", o);
        messageData.put("schema", ContextHandler.getSchema());
        TransactionSendResult transactionSendResult =
                rocketMQTemplate.sendMessageInTransaction(group, topic,
                        MessageBuilder.withPayload(messageData)
                                .setHeader(RocketMQHeaders.TRANSACTION_ID, generateUUIDNumber())
                                .setHeader("schema", ContextHandler.getSchema()).build(),
                        messageData);
        log.info("Send half message successfully!");
        String localTransactionState = transactionSendResult.getLocalTransactionState().toString();
        return "COMMIT_MESSAGE".equals(localTransactionState) ? 1 : 0;
    }

    private static synchronized String generateUUIDNumber() {
        return UUID.randomUUID().toString();
    }

}
